import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import ResizeObserver from 'resize-observer-polyfill';
import { MyContext } from '@/untils/context'
import { useContext } from 'react';

interface BarChartProps {
  category: string[],
  value: number[],
}

const BarChart: React.FC<BarChartProps> = ({ category, value }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  let chartInstance: echarts.ECharts | null = null;
  const size = useContext(MyContext);
  useEffect(() => {
    console.log('=1=1=1==1')
    if (chartRef.current) {
      chartInstance = echarts.init(chartRef.current);
      const options: echarts.EChartsOption = {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          show: false
        },
        grid: {
          top: 50,
          left: 30,
          right: 20,
          bottom: 80
        },
        xAxis: {
          data: category,
        },
        yAxis: {},
        series: [{
          name: 'Value',
          type: 'bar',
          data: value,
          itemStyle: {
            color: {
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              type: "linear",
              global: false,
              colorStops: [{
                offset: 0,
                color: "#e7ad00"
              }, {
                offset: 1,
                color: "#026ee7"
              }]
            },
            borderRadius: 30
          },
        }]
      };

      chartInstance.setOption(options);
      const resizeHandler = () => {
        if (chartInstance) {
          chartInstance.resize();
        }
      };
      // 自适应父亲元素尺寸的变化
      const resizeObserver = new ResizeObserver(() => {
        if (chartInstance) {
          chartInstance.resize();
        }
      });
      resizeObserver.observe(chartRef.current);
      window.addEventListener('resize', resizeHandler);

      return () => {
        if (chartInstance) {
          window.removeEventListener('resize', resizeHandler);
          chartInstance.dispose();
          chartInstance = null;
        }
      };
    }
  }, [category, value, size]);

  return <div ref={chartRef} style={{ width: '100%', height: '100%' }} />;
};

export default BarChart;
